package com.borzaindustries.mkdummy;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.Toast;

public class CreateTextDummy extends Activity implements Runnable {
	// CONSTANTS
	public final String DIRECTORY = "DIRECTORY";
	public final String NAME = "NAME";
	public final String PARAGRAPH_COUNT = "PARAGRAPH_COUNT";
	public final String WORDS_IN_PARAGRAPH = "WORDS_IN_PARAGRAPH";
	public final String FILE_TYPE_IS_LOREM_IPSUM = "FILE_TYPE";
	public final int PROGRESS_DIALOG = 0;
	public final int CONFIRM_OVEWRTITE = 1;

	private boolean usingSaveInsteadOfView = true;
	private boolean cancel = false;
	private File file;
	private String HTML;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_text_dummy);
		attachEventListeners();
		restorePrefs();
	}

	@Override
	protected void onResume() {
		super.onResume();
		restorePrefs();
	}

	private void attachEventListeners() {
		this.setTitle(this.getString(R.string.create_text_title));
		((ImageButton) findViewById(R.id.button_browse_dir))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						browseDir();
					}
				});
		((ImageButton) findViewById(R.id.button_random_name))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						setName(getRandomName());
					}
				});
		((ImageButton) findViewById(R.id.button_random_paragraph_count))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						setParagraphCount(getRandomParagraphCount());
					}
				});
		((ImageButton) findViewById(R.id.button_random_words_in_paragraph))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						setWordsInParagraph(getRandomWordsInParagraph());
					}
				});
		((Button) findViewById(R.id.save))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						createDummyTextFile();
					}
				});
		((Button) findViewById(R.id.view))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						viewDummyTextFile();
					}
				});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case CONFIRM_OVEWRTITE:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					getString(R.string.file_already_exists_overwrite,
							file.getName()))
					.setTitle(R.string.app_name)
					.setCancelable(true)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// continue with dummy
									dialog.dismiss();
									if (usingSaveInsteadOfView)
										startCreateDummyThread();
									else
										startViewDummyThread();
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							});
			return builder.create();
		case PROGRESS_DIALOG:
			ProgressDialog progressDialog = new ProgressDialog(this);
			progressDialog
					.setMessage(this.getText(R.string.creating_file_wait));
			progressDialog.setCancelable(true);
			progressDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					cancel = true;
				}
			});
			return progressDialog;
		default:
			return null;
		}
	}

	// DIRECTORY BROWSING
	private void browseDir() {
		// decode test string
		String path = getDirectory();
		Intent intent = new Intent(getBaseContext(), DirectoryBrowser.class);
		intent.putExtra(DirectoryBrowser.SELECTED_PATH, path);
		startActivityForResult(intent, DirectoryBrowser.BROWSE_DIR);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == DirectoryBrowser.BROWSE_DIR) {
			if (resultCode != RESULT_OK)
				return;
			String directory = data
					.getStringExtra(DirectoryBrowser.SELECTED_PATH);
			setDirectory(directory);
		}
	}

	// END DIRECTORY BROWSING

	// PREFERENCES
	private void restorePrefs() {
		SharedPreferences settings = getPreferences(MODE_PRIVATE);
		// name from preferences
		String name = settings.getString(NAME, "");
		if (name == "")
			name = getRandomName();
		setName(name);

		// check for size in preferences
		int pars = settings.getInt(PARAGRAPH_COUNT, -1);
		if (pars == -1)
			pars = getRandomParagraphCount();
		setParagraphCount(pars);
		int wip = settings.getInt(WORDS_IN_PARAGRAPH, -1);
		if (wip == -1)
			wip = getRandomWordsInParagraph();
		setWordsInParagraph(wip);

		// check for directory in preferences
		String directory = settings.getString(DIRECTORY, "");
		if (directory == "")
			directory = "/sdcard"; // default to /sdcard
		setDirectory(directory);
		// set file type
		boolean fileTypeLoremIpsum = settings.getBoolean(
				FILE_TYPE_IS_LOREM_IPSUM, true);
		((RadioButton) findViewById(R.id.file_lorem_ipsum))
				.setChecked(fileTypeLoremIpsum);
		((RadioButton) findViewById(R.id.file_random_text))
				.setChecked(!fileTypeLoremIpsum);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// save all settings
		SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
		editor.putString(NAME, getName());
		editor.putString(DIRECTORY, getDirectory());
		editor.putInt(PARAGRAPH_COUNT, getParagraphCount());
		editor.putInt(WORDS_IN_PARAGRAPH, getWordsInParagraph());
		editor.putBoolean(FILE_TYPE_IS_LOREM_IPSUM, isFileTypeLoremIpsum());
		editor.commit();
	}

	// UI GETTERS AND SETTERS
	private boolean isFileTypeLoremIpsum() {
		return ((RadioButton) findViewById(R.id.file_lorem_ipsum)).isChecked();
	}

	private int getWordsInParagraph() {
		try {
			int value = Integer
					.parseInt(((EditText) findViewById(R.id.edit_words_in_paragraph))
							.getText().toString());
			return value;
		} catch (NumberFormatException e) {
			return -1;
		}
	}

	private int getRandomWordsInParagraph() {
		return Randomizer.getInstance().getRandomNumber(20, 200);
	}

	private void setWordsInParagraph(int wip) {
		((EditText) findViewById(R.id.edit_words_in_paragraph)).setText(Integer
				.toString(wip));
	}

	private int getParagraphCount() {
		try {
			int value = Integer
					.parseInt(((EditText) findViewById(R.id.edit_paragraph_count))
							.getText().toString());
			return value;
		} catch (NumberFormatException e) {
			return -1;
		}
	}

	private int getRandomParagraphCount() {
		return Randomizer.getInstance().getRandomNumber(1, 100);
	}

	private void setParagraphCount(int pars) {
		((EditText) findViewById(R.id.edit_paragraph_count)).setText(Integer
				.toString(pars));
	}

	private String getDirectory() {
		return ((EditText) findViewById(R.id.edit_dir)).getText().toString();
	}

	private void setDirectory(String directory) {
		((EditText) findViewById(R.id.edit_dir)).setText(directory);
	}

	private String getName() {
		return ((EditText) findViewById(R.id.edit_name)).getText().toString();
	}

	private String getRandomName() {
		return Randomizer.getInstance().getShortRandomString() + ".tmp";
	}

	private void setName(String name) {
		((EditText) findViewById(R.id.edit_name)).setText(name);
	}

	//

	protected void test() {
		LoremIpsumGenerator gen = new LoremIpsumGenerator();
		gen.load();
		String s = gen.generateParagraph(20);
		Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
	}

	private void createDummyTextFile() {
		String directory = getDirectory();
		String name = getName();

		file = new File(directory, name);
		if (file.exists()) {
			showDialog(CONFIRM_OVEWRTITE); // TODO dialog CONFIRM_OVEWRITE HAS
											// TO CALL startCreateDummyThread
			return;
		}
		startCreateDummyThread();
	}

	protected void viewDummyTextFile() {
		// generate the text and put it into a viewer
		startViewDummyThread();
	}

	public void startCreateDummyThread() {
		usingSaveInsteadOfView = true;
		showDialog(PROGRESS_DIALOG);
		Thread thread = new Thread(this);
		thread.start();
	}

	protected void startViewDummyThread() {
		usingSaveInsteadOfView = false;
		showDialog(PROGRESS_DIALOG);
		Thread thread = new Thread(this);
		thread.start();
	}

	// DUMMY CREATE THREAD
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			dismissDialog(PROGRESS_DIALOG);
			if (msg.what == RESULT_OK) {
				if (usingSaveInsteadOfView)
					Toast.makeText(
							CreateTextDummy.this,
							CreateTextDummy.this.getString(
									R.string.file_created_successfully,
									file.getName()), Toast.LENGTH_SHORT).show();
				else {
					Toast.makeText(
							CreateTextDummy.this,
							CreateTextDummy.this
									.getString(R.string.dummy_text_created_opening),
							Toast.LENGTH_SHORT).show();
					viewCreatedDummyText();
				}
			} else
				Toast.makeText(
						CreateTextDummy.this,
						CreateTextDummy.this
								.getString(R.string.file_not_created),
						Toast.LENGTH_SHORT).show();
		}
	};

	@Override
	public void run() {
		try {
			boolean result;
			if (usingSaveInsteadOfView)
				result = saveTextFile(file, getParagraphCount(),
						getWordsInParagraph(), isFileTypeLoremIpsum());
			else
				result = generateDummyTextForView(file, getParagraphCount(),
						getWordsInParagraph(), isFileTypeLoremIpsum());
			if (result) {
				handler.sendEmptyMessage(RESULT_OK);
			} else {
				handler.sendEmptyMessage(RESULT_CANCELED);
			}
		} catch (Exception e) {
			handler.sendEmptyMessage(RESULT_CANCELED);
		}
	}

	protected void viewCreatedDummyText() {
		Intent intent = new Intent(getBaseContext(), ResultActivity.class);
		intent.putExtra("html", HTML);
		startActivity(intent);
	}

	private boolean generateDummyTextForView(File file, int paragraphCount,
			int wordsInParagraph, boolean areWeGeneratingLoremIpsum) {
		IStringsGenerator gen;
		if (areWeGeneratingLoremIpsum) {
			gen = new LoremIpsumGenerator();
		} else {
			gen = new RandomStringsGenerator();
		}
		gen.load();
		StringBuilder builder = new StringBuilder();
		builder.append("<html><head></head><body>");
		for (int p = 0; p < paragraphCount; p++) {
			if (cancel)
				return false;
			builder.append("<p>");
			builder.append(gen.generateParagraph(wordsInParagraph));
			builder.append("</p>");
		}
		builder.append("</body></html>");
		HTML = builder.toString();
		return true;
	}

	private boolean saveTextFile(File file, int paragraphs, int words,
			boolean UseLoremIpsum) {
		LoremIpsumGenerator gen = new LoremIpsumGenerator();
		gen.load();
		String s = gen.generateParagraph(words);
		Toast.makeText(CreateTextDummy.this, s, Toast.LENGTH_SHORT).show();
		return false;
	}
}
